package com.fingard.dsp.bank.directbank.gac01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBalance;
import com.fingard.dsp.bank.reqrespobj.balance.Req7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.Req7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7505HisBalQry;
import com.fingard.dsp.bank.reqrespobj.balance.RetAts7506BalQry;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsBalDetail;
import com.fingard.dsp.bank.reqrespobj.balance.detail.RetAtsHisBalDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;

/**
 * @author Parker on 2020-06-18.
 * @version 1.0
 */
public class GAC01Balance extends GAC01Base implements IBalance {
    @Override
    public RetAts7506BalQry d_7506_BalQry(Req7506BalQry p_req7506) throws Exception {
        //余额查询返回ATS的对象
        RetAts7506BalQry retAts = new RetAts7506BalQry(p_req7506.reqHeader);
        retAts.writeStart();//写返回ATS的统一头部信息
        StringBuilder messageStr = new StringBuilder();
        int successCount = 0;
        try {
            String transCode = "5";
            while (p_req7506.readRecord()) {
                RetAtsBalDetail tmpRetDetail = new RetAtsBalDetail();
                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                writeCommonHeader(xmlWriter);
                xmlWriter.writeStartElement("Iss_Itreasury");
                xmlWriter.writeStartElement("QueryReq");
                xmlWriter.writeElementString("OperationType", transCode);//操作类型
                xmlWriter.writeElementString("SystemID", bankFront.termid);//系统ID
                xmlWriter.writeStartElement("QueryContent");
                xmlWriter.writeElementString("AccountCode", p_req7506.readedDetail.actNum);
                xmlWriter.writeEndDocument();

                String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString(), p_req7506.reqHeader.transType, p_req7506.reqHeader.transType);
                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/ApplyCode");//为空的时候，返回正常
                        String returnMsg = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/StatusDec");
                        if (StringHelper.isNullOrEmpty(returnCode)) {
                            successCount++;
                            tmpRetDetail.respCode = "0";
                            tmpRetDetail.respInfo = "查询成功";
                            tmpRetDetail.actCur = p_req7506.readedDetail.actCur;
                            tmpRetDetail.actNum = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/QueryRen/RenContent/AccountNo");
                            tmpRetDetail.actArea = p_req7506.readedDetail.actArea;

                            tmpRetDetail.currBal = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/QueryRen/RenContent/Balance");//余额
                            tmpRetDetail.availBal = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/QueryRen/RenContent/AvailableBalance");//可用余额
                        } else {
                            tmpRetDetail.respCode = "-1";
                            tmpRetDetail.respInfo = returnMsg;
                        }
                        retAts.writeRetDetail(tmpRetDetail, p_req7506.isBatch);
                    } else {
                        messageStr.append("账号:").append(p_req7506.readedDetail.actNum).append(",查询余额失败：").append(tmpSbMsg).append(";\r\n");
                    }
                } else {
                    messageStr.append("账号:").append(p_req7506.readedDetail.actNum).append(",查询余额失败：").append(tmpRetBkStr[1]).append(";\r\n");
                }
            }
            if (successCount > 0) {
                retAts.writeRespCode("0");
                if (messageStr.toString().length() > 0) {
                    retAts.writeRespInfo(messageStr.toString());
                } else {
                    retAts.writeRespInfo("查询成功");
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(messageStr.toString());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.writeRespCode("-1");
            messageStr.append("查询异常：").append(ex.getMessage()).append("\r\n");
            retAts.writeRespInfo(messageStr.toString());
        } finally {
            if (messageStr.length() > 0) {
                WriteBankLogLn(messageStr.toString());
            }
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAts7505HisBalQry d_7505_BalQry(Req7505HisBalQry p_req7505) throws Exception {
        RetAts7505HisBalQry retAts = new RetAts7505HisBalQry(p_req7505.reqHeader);
        retAts.writeStart();
        StringBuilder tmpRespInfo = new StringBuilder();
        try {
            String transCode = "4";
            //银行接口限制,开始日期与结束日期只能间隔31天
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7505.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7505.getDateTo());
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            while (tmpIntDateFrom <= tmpIntDateTo) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }

                XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
                writeCommonHeader(xmlWriter);
                xmlWriter.writeStartElement("Iss_Itreasury");
                xmlWriter.writeStartElement("QueryReq");
                xmlWriter.writeElementString("OperationType", transCode);//操作类型
                xmlWriter.writeElementString("SystemID", bankFront.termid);//系统ID
                xmlWriter.writeStartElement("QueryContent");
                xmlWriter.writeElementString("AccountCode", p_req7505.actNum);//账号
                xmlWriter.writeElementString("ExcuteStart", Format.Date10Format.format(tmpCalendarFrom.getTime()));//开始日期
                xmlWriter.writeElementString("ExcuteEnd", Format.Date10Format.format(tmpClndrStepTo.getTime()));//结束日期
                xmlWriter.writeEndDocument();

                String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString(), p_req7505.reqHeader.transType, p_req7505.reqHeader.transType);

                if (tmpRetBkStr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String returnCode = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/ApplyCode");
                        String returnMsg = tmpBkReader.getFirstTextNotNull("/Iss_Itreasury/InstrRen/RenContent/StatusDec");
                        if (StringHelper.isNullOrEmpty(returnCode)) {
                            while (tmpBkReader.read("/Iss_Itreasury/QueryRen/RenContent/")) {
                                RetAtsHisBalDetail tmpRetDetail = new RetAtsHisBalDetail();
                                String tmpETYDAT = tmpBkReader.readedXElement.getSingleText("Date");
                                if (tmpETYDAT.length() == 8) {
                                    tmpRetDetail.balDate = tmpETYDAT.substring(0, 4) + "-" + tmpETYDAT.substring(4, 6) + "-" + tmpETYDAT.substring(6, 8);
                                } else {
                                    tmpRetDetail.balDate = tmpETYDAT;
                                }
                                tmpRetDetail.availBal = tmpBkReader.readedXElement.getSingleText("Balance");
                                tmpRetDetail.actBal = StringHelper.amountDivide100(tmpBkReader.readedXElement.getSingleText("Balance"));
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            tmpRespInfo.append("查询").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("至")
                                    .append(Format.Date8Format.format(tmpCalendarTo.getTime())).append("日失败,原因:").append(returnMsg + "\r\n");
                        }
                    } else {
                        tmpRespInfo.append("查询").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("至")
                                .append(Format.Date8Format.format(tmpCalendarTo.getTime())).append("日失败,原因:").append(tmpSbMsg.toString() + "\r\n");
                    }
                } else {
                    tmpRespInfo.append("查询").append(Format.Date8Format.format(tmpCalendarFrom.getTime())).append("至")
                            .append(Format.Date8Format.format(tmpCalendarTo.getTime())).append("日失败,原因:").append(tmpRetBkStr[1] + "\r\n");
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);//下个月
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
            if (retAts.getWrittenRdCount() == 0 && tmpRespInfo.length() == 0) {
                retAts.writeRespCode("0");
                retAts.writeRespInfo("交易为空");
            } else if (tmpRespInfo.toString().length() > 0) {
                retAts.writeRespInfo(tmpRespInfo.toString());
            } else {
                retAts.writeRespInfo("查询成功");
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
            e.printStackTrace();
            retAts.writeRespCode("-1");
            tmpRespInfo.append("查询异常：").append(e.getMessage()).append("\r\n");
            retAts.writeRespInfo(tmpRespInfo.toString());
        } finally {
            if (tmpRespInfo.length() > 0) {
                WriteBankLogLn(tmpRespInfo.toString());
            }
        }
        retAts.writeEnd();
        return retAts;
    }
}
